package cn.zhouyafeng.itchat4j.demo.demo2;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.zhouyafeng.itchat4j.Wechat;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;
import cn.zhouyafeng.itchat4j.utils.enums.MsgTypeEnum;
import cn.zhouyafeng.itchat4j.utils.tools.DownloadTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图灵机器人示例
 * @author https://github.com/yaphone
 * @version 1.0
 * @date 创建时间：2017年4月24日 上午12:13:26
 */
public class TulingRobot implements IMsgHandlerFace {
    private static Logger logger = LoggerFactory.getLogger(TulingRobot.class);
    private Core core;
    String tulingApi = "http://www.tuling123.com/openapi/api";
    String[] apiKey = {"597b34bea4ec4c85a775c469c84b6817", "0df614f5bf4b40a1a4488d337cad36aa"}; // 这里是我申请的图灵机器人API接口，每天只能5000次调用，建议自己去申请一个，免费的:)


    @Override
    public String textMsgHandle(BaseMsg msg) {
        String result = "";
        String text = msg.getText();
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("key", apiKey[1]);
        paramMap.put("info", text);
        paramMap.put("userid", "123456");
        String paramStr = JSON.toJSONString(paramMap);
        logger.info("收到来自 {} 的文本消息:{}", CollUtil.findOne(core.getContactList(), o -> Objects.equals(o.getString("UserName"), msg.getFromUserName())).getString(
                "RemarkName"), text);
        if (msg.isGroupMsg()) {
            return null;
        }
        try {
            HttpEntity entity = core.getMyHttpClient().doPost(tulingApi, paramStr);
            result = EntityUtils.toString(entity, "UTF-8");
            JSONObject obj = JSON.parseObject(result);
            if (obj.getString("code").equals("100000")) {
                result = obj.getString("text");
//                logger.info("回复:" + result);
            } else {
                logger.error("处理有误");
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return result;
    }

    @Override
    public String picMsgHandle(BaseMsg msg) {
        String fileName = String.valueOf(new Date().getTime());
        String voicePath = "D://itchat4j/pic" + File.separator + fileName + ".png";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), voicePath,core);
//        logger.info("收到图片:" + JSONUtil.toJsonStr(msg));
        return null;
    }

    @Override
    public String voiceMsgHandle(BaseMsg msg) {
        String fileName = String.valueOf(new Date().getTime());
        String voicePath = "D://itchat4j/voice" + File.separator + fileName + ".mp3";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath,core);
//        logger.info("收到语音:" + JSONUtil.toJsonStr(msg));
        return null;
    }

    @Override
    public String viedoMsgHandle(BaseMsg msg) {
        String fileName = String.valueOf(new Date().getTime());
        String viedoPath = "D://itchat4j/viedo" + File.separator + fileName + ".mp4";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), viedoPath,core);
//        logger.info("收到视频:" + JSONUtil.toJsonStr(msg));
        return null;
    }

    @Override
    public String nameCardMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void sysMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
    }

    @Override
    public String verifyAddFriendMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String mediaMsgHandle(BaseMsg msg) {
        String filePath = "D://itchat4j/file" + File.separator + msg.getFileName();
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.MEDIA.getType(), filePath,core);
//        logger.info("收到文件:" + JSONUtil.toJsonStr(msg));
        return null;
    }

    @Override
    public void setCore(Core core) {
        this.core = core;
    }

    @Override
    public Core getCore() {
        return core;
    }

    public static void main(String[] args) {
        IMsgHandlerFace msgHandler = new TulingRobot();
        Wechat.newClient(msgHandler);
    }
}
